<?php
namespace Modules\Frontend\Controllers;

class UserController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute() {
		\Components\Utils::isClosedFrontent($this);
	}

	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function indexAction() {
		$service = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success','user'=>$service['user']]);
	}

	public function passwordAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$put = $this -> request -> getPut();
		if(!$this -> security -> checkHash($put['oldPassword'], $serviceUser['user'] -> password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'旧密码错误']);
		}

		if(!$this -> security -> checkHash($put['safePassword'], $serviceUser['user'] -> safe_password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']);
		}

		$service = $this -> account::getServiceInstance() -> update($serviceUser['user']->user_id,['password'=>$this -> security -> hash($put['newPassword'])]);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'修改成功']);
	}

	public function safePasswordAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$put = $this -> request -> getPut();
		if(!$this -> security -> checkHash($put['oldSafePassword'], $serviceUser['user'] -> safe_password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'旧安全密码密码错误']);
		}

		if(!$this -> security -> checkHash($put['password'], $serviceUser['user'] -> password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'密码错误']);
		}

		$service = $this -> account::getServiceInstance() -> update($serviceUser['user']->user_id,['safe_password'=>$this -> security -> hash($put['newSafePassword'])]);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'修改成功']);
	}
}